/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.zzzzzz.app.account.controller;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.zzzzzz.app.account.NoSuchUserException;
import com.zzzzzz.app.account.UserActiveException;
import com.zzzzzz.app.account.model.vo.LoginVo;
import com.zzzzzz.app.account.service.UserManager;

/**
 * Web MVC controller that handles security-related web requests, such as login and logout.
 */

@Controller
public class SecurityController {

	@Resource
	private UserManager userManager;

	@RequiresGuest
    @RequestMapping(value="/login",method= RequestMethod.GET)
    public String showLoginForm(Model model, @ModelAttribute LoginVo loginVo) {
		model.addAttribute("cur", "login");
        return "account/login";
    }

	@RequiresGuest
    @RequestMapping(value="/login",method= RequestMethod.POST)
    public String login(Model model, @ModelAttribute LoginVo loginVo, BindingResult result) throws Exception {
        if(result.hasErrors()) {
    		result.reject("message.error.process.request");
            return showLoginForm(model, loginVo);
        }
        try {
	        // login
			userManager.login(loginVo.getEmail(), loginVo.getPassword(), loginVo.isRememberMe());
    		return "redirect:/dashboard";
			
		} catch (Exception e) {
			if(e instanceof NoSuchUserException) {
	            result.reject("message.error.login.generic");
			}else if(e instanceof AuthenticationException) {
	            result.reject("message.error.login.generic");
			}else if(e instanceof UserActiveException) {
        		result.reject( "message.error.login.account.unactivated");
			}else {
				logger.error(e.getMessage(), e);
				throw e; // handle by Spring
			}
		}

        return showLoginForm(model, loginVo);
        
    }

    @RequestMapping("/logout")
    public String logout() {
        SecurityUtils.getSubject().logout(); //removes all identifying information and invalidates their session too.
        return "redirect:/";
    }
    
	private static Logger logger = Logger.getLogger(SecurityController.class);
}
